package com.yuanrui.circle.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanrui.circle.api.common.PageInfo;
import com.yuanrui.circle.api.common.PageResult;
import com.yuanrui.circle.api.enums.IsDeletedFlagEnum;
import com.yuanrui.circle.api.req.GetShareMomentReq;
import com.yuanrui.circle.api.req.RemoveShareMomentReq;
import com.yuanrui.circle.api.req.SaveMomentCircleReq;
import com.yuanrui.circle.api.vo.ShareMomentVO;
import com.yuanrui.circle.server.dao.ShareMomentDao;
import com.yuanrui.circle.server.entity.ShareMoment;
import com.yuanrui.circle.server.entity.UserInfo;
import com.yuanrui.circle.server.rpc.UserRpc;
import com.yuanrui.circle.server.service.ShareMomentService;
import com.yuanrui.circle.server.util.LoginUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 动态信息(ShareMoment)表服务实现类
 *
 * @author makejava
 * @since 2024-07-28 16:15:01
 */
@Service("shareMomentService")
public class ShareMomentServiceImpl extends ServiceImpl<ShareMomentDao, ShareMoment> implements ShareMomentService {
    @Resource
    private ShareMomentDao shareMomentDao;
    @Resource
    private UserRpc userRpc;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ShareMoment queryById(Long id) {
        return this.shareMomentDao.queryById(id);
    }


    /**
     * 新增数据
     *
     * @param shareMoment 实例对象
     * @return 实例对象
     */
    @Override
    public ShareMoment insert(ShareMoment shareMoment) {
        this.shareMomentDao.insert(shareMoment);
        return shareMoment;
    }

    /**
     * 修改数据
     *
     * @param shareMoment 实例对象
     * @return 实例对象
     */
    @Override
    public ShareMoment update(ShareMoment shareMoment) {
        this.shareMomentDao.update(shareMoment);
        return this.queryById(shareMoment.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.shareMomentDao.deleteById(id) > 0;
    }

    @Override
    public Boolean saveMoment(SaveMomentCircleReq req) {
        ShareMoment shareMoment = new ShareMoment();
        shareMoment.setCircleId(req.getCircleId());
        shareMoment.setContent(req.getContent());
        if (!CollectionUtils.isEmpty(req.getPicUrlList())) {
            shareMoment.setPicUrls(JSON.toJSONString(req.getPicUrlList()));
        }
        shareMoment.setReplyCount(0);
        shareMoment.setCreatedBy(LoginUtil.getLoginId());
        shareMoment.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        shareMoment.setCreatedTime(new Date());
        return shareMomentDao.insert(shareMoment) > 0;
    }

    @Override
    public PageResult<ShareMomentVO> getMoments(GetShareMomentReq req) {
        QueryWrapper<ShareMoment> shareMomentQueryWrapper = new QueryWrapper<>();
        shareMomentQueryWrapper.eq("circle_id", req.getCircleId())
                .eq("is_deleted", IsDeletedFlagEnum.UN_DELETED.getCode())
                .orderByDesc("circle_id");
        PageInfo pageInfo = req.getPageInfo();
        Page<ShareMoment> page = new Page<>(pageInfo.getPageNo(), pageInfo.getPageSize());
        Page<ShareMoment> pageRes = super.page(page, shareMomentQueryWrapper);
        PageResult<ShareMomentVO> pageResult = new PageResult<>();
        List<ShareMoment> records = pageRes.getRecords();
        List<String> userNames = records.stream().map(ShareMoment::getCreatedBy).distinct().toList();
        Map<String, UserInfo> userInfoMap = userRpc.batchGetUserInfo(userNames);
        UserInfo userInfo = new UserInfo();
        List<ShareMomentVO> list = records.stream().map(shareMoment -> {
            ShareMomentVO shareMomentVO = new ShareMomentVO();
            shareMomentVO.setId(shareMoment.getId());
            shareMomentVO.setContent(shareMoment.getContent());
            shareMomentVO.setCircleId(shareMoment.getCircleId());
            if (Objects.nonNull(shareMoment.getPicUrls())) {
                shareMomentVO.setPicUrlList(JSON.parseArray(shareMoment.getPicUrls(), String.class));
            }
            shareMomentVO.setReplyCount(shareMoment.getReplyCount());
            shareMomentVO.setCreatedTime(shareMoment.getCreatedTime().getTime());
            UserInfo userInfo1 = userInfoMap.getOrDefault(shareMoment.getCreatedBy(), userInfo);
            shareMomentVO.setUserName(userInfo1.getNickName());
            shareMomentVO.setUserAvatar(userInfo1.getAvatar());
            return shareMomentVO;
        }).toList();
        pageResult.setResult(list);
        pageResult.setPageNo(pageInfo.getPageNo());
        pageResult.setPageSize(pageInfo.getPageSize());
        pageResult.setTotal((int) pageRes.getTotal());
        return pageResult;
    }

    @Override
    public Boolean removeMoment(RemoveShareMomentReq req) {
        UpdateWrapper<ShareMoment> shareMomentUpdateWrapper = new UpdateWrapper<>();
        shareMomentUpdateWrapper.eq("id", req.getId())
                .set("update_by", LoginUtil.getLoginId())
                .set("is_deleted", IsDeletedFlagEnum.DELETED.getCode())
                .set("update_time", new Date());
        return super.update(shareMomentUpdateWrapper);
    }
}
